<template>
  <div class="hello">
    <audio ref="player" :src="curUrl" autoplay></audio>
  </div>
</template>

<script>
import {mapGetters, mapMutations } from 'vuex';
import List from '@/api/index';
import { Dialog } from 'vant';
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      curUrl:'',
    }
  },
  computed:{
    ...mapGetters(['getIsPlay', 'getSongCur','getSongList','getSsongCurTime'])
  },
  mounted() {
      this.addEventHandle();
      
  },
  beforeDestroy(){
      this.removeEventHandle();
      
  },
  methods:{
    ...mapMutations(['setSongCurTime','setSongTime', 'setSongCur', 'setIsPlay']),
    addEventHandle() {
        this.$refs.player.addEventListener("timeupdate",this.currentTimeHandle);
        this.$refs.player.addEventListener("ended",this.songEndHandle);
        //play
        this.$refs.player.addEventListener("play",this.songPlayHandle);
    },
    removeEventHandle(){
        this.$refs.player.removeEventListener("timeupdate",this.currentTimeHandle);
        this.$refs.player.removeEventListener("ended", this.songEndHandle);
        this.$refs.player.removeEventListener("paly", this.songPlayHandle);
    },
    songPlayHandle(){
      this.setSongTime(this.$refs.player.duration);
      this.setIsPlay(true);
      console.log('song start');
    },
    currentTimeHandle(){
      //this.$refs.player.currentTime
      this.setSongCurTime(this.$refs.player.currentTime);

    },songEndHandle(){
        //完毕
        if(this.getSongList.length == this.getSongCur+1) this.setSongCur(0);
        else this.setSongCur(this.getSongCur+1);
        
        
    },
    getUrl(id){
      let _this = this;
      List.getSongUrl(id).then(function(res){
            _this.curUrl = res.data.data[0].url;
            //_this.setSongTime(_this.$refs.player.duration);
            if(!_this.curUrl) {
              // console.log('当前歌曲无版权');
              Dialog.alert({
              message: '当前歌曲无版权',
              theme: 'round-button',
            }).then(() => {
              // on close
            });
          }
      })
    }
  },
  watch:{
    getIsPlay(){
      if(this.getIsPlay){
        this.$refs.player.play();
      }else{
        this.$refs.player.pause();
      }
    },
    getSongCur(){
      if(this.getSongCur < this.getSongList.length){
         this.getUrl(this.getSongList[this.getSongCur].id);
      }else if(this.getSongList.length > 0){
        this.getUrl(this.getSongList[0].id);
      }
    },
    getSsongCurTime(){
      this.$refs.player.currentTime = this.getSsongCurTime;
    }
    
  }
}
</script>
